let content = document.getElementById("content");
let ans = "";

function display(num) {
    content.innerHTML = content.innerHTML + num;
    ans = content.innerHTML;
}
function cal() {
    try {
        ans = content.innerHTML.replace("π", "3.1415926536");
        content.innerHTML = eval(ans);
    } catch (error) {
        content.innerHTML = '<div class="error_message">' + error.name + '</div>';
        console.log(error.name + ":" + error.message);
        setTimeout(delAll,2000);
    }
}
function delAll() {
    content.innerHTML = "";
    ans = content.innerHTML;
}
function del() {
    content.innerHTML = content.innerHTML.slice(0, content.innerHTML.length - 1);
    ans = content.innerHTML;
}

function getPI() {
    content.innerHTML = content.innerHTML + "π";
}

function inverse() {
    content.innerHTML = content.innerHTML.slice(0, content.innerHTML.length - 1)
    +"1/" + content.innerHTML.slice(content.innerHTML.length-1);
    ans = content.innerHTML;
}

function factorial() {
    ans = content.innerHTML; 
    let j = ans.length-1;
    let num = "";
    while (j >= 0){
        if (!(ans[j] >= '0' && ans[j] <= '9')) break;
        num += ans[j];
        j--;
    }
    j++;
    console.log("j: "+ j);
    console.log(num);
    num = num + "";
    num = num.split("").reverse().join("");
    let reg = new RegExp('(.*)' + ans.slice(j));
    console.log("ans before: " + ans);
    ans = ans.replace(reg, "$1" + calfactorial(num));
    console.log("ans after: " + ans);
    content.innerHTML = ans;
}

function calfactorial(n){
    n = eval(n);
    let res = 1;
    for(let i=1;i<=n;i++){
        res*=i;
    }
    return res+"";
}

function sqrt() {
    ans = content.innerHTML;   
    let j = ans.length - 1;
    let num = "";
    while (j >= 0) {
        if (!((ans[j] >= '0' && ans[j] <= '9')||ans[j]=='.')) break;
        num += ans[j];
        j--;
    }
    j++;
    console.log("j: " + j);
    console.log(num);
    num = num + "";
    num = num.split("").reverse().join("");
    ans = ans.replace(ans.slice(j), Math.sqrt(num));
    console.log("ans: " + ans);
    content.innerHTML = ans;
}